package com.kawa.kemanage.controller;

import com.github.pagehelper.PageInfo;
//import com.kawa.kemanage.entity.DTO.CommentDto;
//import com.kawa.kemanage.entity.DTO.ReadMessageDTO;
import com.kawa.kemanage.entity.NewsComments;
import com.kawa.kemanage.entity.dto.CommentDTO;
import com.kawa.kemanage.service.NewsCommentsService;
import com.kawa.kemanage.util.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Validated
@RestController
@RequestMapping({"/api/comments","/app/comments"})
@CrossOrigin
@Tag(name = "评论管理接口", description = "评论的增删改查等操作")
public class NewsCommentsController {

    @Autowired
    private NewsCommentsService commentsService;

    @Operation(summary = "获取文章评论列表", description = "分页获取指定文章的评论列表")
    @GetMapping("/article/{contentId}")
    //@Cacheable(value = "comments", key = "'article-' + #contentId + '-' + #pageNo + '-' + #pageSize", unless = "#result.code != 200")
    public Result getArticleComments(
            @Parameter(description = "文章ID") @PathVariable Long contentId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNo,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            PageInfo<NewsComments> pageInfo = commentsService.getCommentList(pageNo, pageSize, contentId);
            return Result.success(pageInfo);
        } catch (Exception e) {
            log.error("获取文章评论列表失败", e);
            return Result.error("获取文章评论列表失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取评论列表", description = "分页获取评论列表，支持按文章ID筛选")
    @GetMapping("/list")
    @Cacheable(value = "comments", key = "#pageNo + '-' + #pageSize + '-' + #contentId", unless = "#result.code != 200")
    public Result getCommentList(
            @Parameter(description = "文章ID") @RequestParam(required = false) Long contentId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNo,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            PageInfo<NewsComments> pageInfo = commentsService.getCommentList(pageNo, pageSize, contentId);
            return Result.success(pageInfo);
        } catch (Exception e) {
            log.error("获取评论列表失败", e);
            return Result.error("获取评论列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取评论列表,所使用的是路径传参
     * @param contentId
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Operation(summary = "获取评论列表", description = "分页获取评论列表，支持按文章ID筛选")
    @GetMapping("/list/{contentId}")
//    @Cacheable(value = "comments", key = "#contentId + '-' + #pageNo + '-' + #pageSize", unless = "#result.code != 200")
    public Result getCommentListById(
            @Parameter(description = "文章ID") @PathVariable(required = false) Long contentId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNo,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            PageInfo<NewsComments> pageInfo = commentsService.getCommentList(pageNo, pageSize, contentId);
            Map<String, Object> resultHashMap = new HashMap<>();
            //存入hashmap，方便为以后添加数据做可拓展性处理
            resultHashMap.put("list", pageInfo.getList());
            resultHashMap.put("total", commentsService.getCommentNumById(contentId));
            resultHashMap.put("totalPage",pageInfo.getPages());
            return Result.success(resultHashMap);
        } catch (Exception e) {
            log.error("获取评论列表失败", e);
            return Result.error("获取评论列表失败: " + e.getMessage());
        }
    }

    @Operation(summary = "搜索评论", description = "根据关键词搜索评论")
    @GetMapping("/search")
    @Cacheable(value = "comments", key = "'search-' + #keyword + '-' + #pageNo + '-' + #pageSize", unless = "#result.code != 200")
    public Result searchComments(
            @Parameter(description = "搜索关键词") @RequestParam String keyword,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNo,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            PageInfo<NewsComments> pageInfo = commentsService.searchComments(keyword, pageNo, pageSize);
            return Result.success(pageInfo);
        } catch (Exception e) {
            log.error("搜索评论失败", e);
            return Result.error("搜索评论失败: " + e.getMessage());
        }
    }

    @Operation(summary = "添加评论", description = "添加新的评论")
    @PostMapping("/add")
    @CacheEvict(value = {"comments"}, allEntries = true)
    public Result addComment(@Valid @RequestBody NewsComments comment) {
        try {
            boolean success = commentsService.addComment(comment);
            return success ? Result.success("评论添加成功") : Result.error("添加评论失败");
        } catch (Exception e) {
            log.error("添加评论失败", e);
            return Result.error("添加评论失败: " + e.getMessage());
        }
    }

    @Operation(summary = "删除评论", description = "根据评论ID删除评论")
    @DeleteMapping("/delete/{commentId}")
    @CacheEvict(value = {"comments"}, allEntries = true)
    public Result deleteComment(@Parameter(description = "评论ID") @PathVariable Long commentId) {
        try {
            boolean success = commentsService.deleteComment(commentId);
            return success ? Result.success("评论删除成功") : Result.error("删除评论失败");
        } catch (Exception e) {
            log.error("删除评论失败", e);
            return Result.error("删除评论失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取评论详情", description = "根据评论ID获取评论详情")
    @GetMapping("/{commentId}")
    @Cacheable(value = "comments", key = "'detail-' + #commentId", unless = "#result.code != 200")
    public Result getCommentById(@Parameter(description = "评论ID") @PathVariable Long commentId) {
        try {
            NewsComments comment = commentsService.getCommentById(commentId);
            return comment != null ? Result.success(comment) : Result.error("评论不存在");
        } catch (Exception e) {
            log.error("获取评论详情失败", e);
            return Result.error("获取评论详情失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取评论的回复列表", description = "获取指定评论的所有回复")
    @GetMapping("/replies/{parentCommentId}")
    @Cacheable(value = "comments", key = "'replies-' + #parentCommentId", unless = "#result.code != 200")
    public Result getReplies(@Parameter(description = "父评论ID") @PathVariable Long parentCommentId) {
        try {
            List<NewsComments> replies = commentsService.getReplies(parentCommentId);
            return Result.success(replies);
        } catch (Exception e) {
            log.error("获取回复列表失败", e);
            return Result.error("获取回复列表失败: " + e.getMessage());
        }
    }

    @Operation(summary = "更新评论点赞数", description = "更新评论的点赞数")
    @PutMapping("/like/{commentId}")
    @CacheEvict(value = {"comments"}, allEntries = true)
    public Result updateLikeCount(
            @Parameter(description = "评论ID") @PathVariable Long commentId,
            @Parameter(description = "点赞增量") @RequestParam(defaultValue = "1") int increment) {
        try {
            boolean success = commentsService.updateLikeCount(commentId, increment);
            return success ? Result.success("点赞更新成功") : Result.error("更新点赞数失败");
        } catch (Exception e) {
            log.error("更新点赞数失败", e);
            return Result.error("更新点赞数失败: " + e.getMessage());
        }
    }

    /**
     * 查询评论总数
     * @return
     */
    @RequestMapping("/commentCount")
    public Result commentCount(){
        try{
            return Result.success(commentsService.commentCount());
        }catch (Exception e){
            log.error("获取评论总数失败",e);
            return Result.error("获取评论总数失败" + e.getMessage());
        }

    }

    @RequestMapping("/commentsByUserId")
    public Result commentsByUserId(Long userId) {
        try {
            return Result.success(commentsService.getCommentsByAuthorId(userId));
        } catch (Exception e) {
            log.error("获取用户评论失败", e);
            return null;
        }
    }

    //单个已读
    @PostMapping("/read")
    public Result readCommentMessage(@RequestBody CommentDTO commentDTO){
        try {
            commentDTO.setUserId(null);
            commentsService.readCommentMessage(commentDTO);
        }catch (Exception e){
            log.error("readSystemMessage error: {SystemMessageController running error,method is readSystemMessage}", e.getMessage());
            return Result.error("已读消息失败：" + e.getMessage());
        }
        return Result.success("消息已读成功！！");
    }

    //批量已读
    @PostMapping("/readall")
    public Result readAllComments(@RequestBody CommentDTO commentDTO){
        try{
            commentDTO.setUserId(null);
            commentsService.readCommentMessage(commentDTO);
        }catch (Exception e){
            return Result.error("已读所有消息失败：" + e.getMessage());
        }
        return Result.success("消息已读成功！！");
    }
}
